package cur.nature.starter.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import cur.nature.framework.core.log.LOG;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;


@Configuration
@ConditionalOnProperty( value = {"cur.core.server.config.mvc.enable"})
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Value("${cur.core.server.config.mvc.swagger:false}")
    private boolean swagger;

    @Value("${cur.core.server.config.mvc.pattern}")
    private String pattern;
    @Value("${cur.core.server.config.mvc.location}")
    private String[] location;

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver resolver = new CookieLocaleResolver();
        // 默认语言
        resolver.setDefaultLocale(new Locale("en","US"));
        resolver.setCookieName("language");
        resolver.setCookieMaxAge(3600); // 1 hour
        return resolver;
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 静态资源访问路径和存放路径配置
        LOG.info("swagger:"+ swagger + ", pattern: " + pattern + ", location : " + location.toString());
//        registry.addResourceHandler(pattern).addResourceLocations(location);
        // swagger访问配置
        if (swagger) {
            registry.addResourceHandler("doc.html","/webjars/**").addResourceLocations("classpath:/META-INF/resources/","classpath:/META-INF/resources/webjars/");
        }
        registry.addResourceHandler("/domain/**")
                .addResourceLocations("classpath:/static/domain/");
        registry.addResourceHandler("/log/**")
                .addResourceLocations("classpath:/static/log/");

        // 假设你的Jar包中的资源位于"classpath:static/"目录下
//        registry.addResourceHandler("/**")
//                .addResourceLocations("classpath:/static/");

        super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns(CorsConfiguration.ALL)
                // 设置允许的方法
                .allowedMethods(CorsConfiguration.ALL)
                // 是否允许证书 不再默认开启
                .allowCredentials(true)

                //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
//                .exposedHeaders(HttpHeaders.CONTENT_DISPOSITION, "")
                .exposedHeaders("token")//设置token可读取，前端才能获取
                // 跨域允许时间
                .maxAge(3600);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = converter.getObjectMapper();
         // 生成JSON时,将所有Long转换成String
//        SimpleModule simpleModule = new SimpleModule();
//        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
//        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
//        objectMapper.registerModule(simpleModule);
         // 时间格式化
//        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//        // 设置返回null转为 空字符串""
//        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<>() {
//            @Override
//            public void serialize(Object paramT, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider) throws IOException, IOException {
//                // 设置返回null转为 空字符串""
//                paramJsonGenerator.writeString("");
//            }
//        });
//        // 设置格式化内容
//        converter.setObjectMapper(objectMapper);

        // 设置对象转换器
        converter.setObjectMapper(new JacksonObjectMapper());
        // TODO 需要替换 json转换的converter ,可能 index会不对
        converters.add(converters.size()-1, converter);
        // 设置文字返回默认为 utf-8
        for (HttpMessageConverter<?> tmpCvt :converters){
            if(tmpCvt instanceof StringHttpMessageConverter){
                //将StringHttpMessageConverter改为utf-8
                ((StringHttpMessageConverter)tmpCvt).setDefaultCharset(StandardCharsets.UTF_8);
            }
        }
    }
}
